//
//  MapViewController.m
//  TabulaImaginarius2
//
//  Created by TA2 on 4/17/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MapViewController.h"


@implementation MapViewController

@synthesize scrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)bundle withMapName:(NSString *)mapName {
    [self initWithNibName:nibNameOrNil bundle:(NSBundle *)bundle];
    currentMapName = mapName; 
    return self;
}

- (void)dealloc {
    [mainMapView release];
    mainMapView = nil;
	[mainSelectionView release];
    mainSelectionView = nil;
    [tokenScrollView release];
    tokenScrollView = nil;
    [eraserButton release];
    eraserButton = nil;
    [mainBackgroundButton release];
    mainBackgroundButton = nil;
    [freehandDrawingButton release];
    freehandDrawingButton = nil;
    [snapDrawingButton release];
    snapDrawingButton = nil;
    [backgroundButton release];
    backgroundButton = nil;
    [objectButton release];
    objectButton = nil;
    [tokenButton release];
    tokenButton = nil;
    [toolBarRemoveButton release];
    toolBarRemoveButton = nil;
    [toolBarReturnButton release];
    toolBarReturnButton = nil;
    [mainMenuRemoveButton release];
    mainMenuRemoveButton = nil;
    [mainMenuReturnButton release];
    mainMenuReturnButton = nil;
    [toolView release];
    toolView = nil;
    [menuView release];
    menuView = nil;
    [super dealloc];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	scrollView.bouncesZoom = NO;
	tokenScrollView.hidden = YES;
	mainSelectionView.zoomGesture.enabled = NO;
	mainSelectionView.contentView = mainMapView;

    fadeIn = [[CABasicAnimation animationWithKeyPath:@"opacity"] retain];
    fadeIn.duration = 1.0;		
    fadeIn.fromValue = [NSNumber numberWithFloat:-0.5]; 
    fadeIn.toValue = [NSNumber numberWithFloat:1.0];
    
    fadeOut = [[CABasicAnimation animationWithKeyPath:@"opacity"] retain];
    fadeOut.duration = 1.0;		
    fadeOut.fromValue = [NSNumber numberWithFloat:1.0]; 
    fadeOut.toValue = [NSNumber numberWithFloat:-0.5];
    
    tokenScrollView.hidden = NO;
    [self loadMap];
    [self displayMap];
    [self doMenuOff:nil];
    [LoadedImages sharedLoadedImages].drawingActivated = YES;
    [LoadedImages sharedLoadedImages].eraserActivated = NO;
    
    mainBackgroundButton.alpha = 0.4;
    snapDrawingButton.alpha = 0.4;
    backgroundButton.alpha = 0.4;
    objectButton.alpha = 0.4;
    tokenButton.alpha = 0.4;
}

- (void)loadMap {
    map = [Map loadMap:currentMapName];
	if (!map) {
		map = [self createNewMap:currentMapName withBackgroundImage:@"background_grass2_1_1"];
	}
}

- (Map *)createNewMap:(NSString *)name withBackgroundImage:(NSString *)backgroundPath {
	Map *newMap = [[[Map alloc] init] autorelease];
	newMap.name = name;
	newMap.size = CGSizeMake(1000000, 1000000);
	newMap.backgroundImage = backgroundPath;
    return newMap;
}

- (void)displayMap {
	[mainMapView displayTiledMap:map withTileSize:CGSizeMake(128, 128) withScale:4];
    
    if (![Players sharedLocalPlayer].isHost) {
        [self disableUI];
    }
    
    PlayerProtocol *playerProtocol = [[[PlayerProtocol alloc] initWithView:mainMapView usingTag:@"PP"] autorelease];
    [playerProtocol setupProtocol];
	[[NetworkController sharedNetworkController].networkProtocols setObject:playerProtocol forKey:[NSString stringWithString:@"PP"]];
    
    BackgroundProtocol *backgroundProtocol = [[[BackgroundProtocol alloc] initWithView:mainMapView usingTag:@"BGP"] autorelease];
    [backgroundProtocol setupProtocol];
    backgroundProtocol.selectionView = mainSelectionView;
	[[NetworkController sharedNetworkController].networkProtocols setObject:backgroundProtocol forKey:[NSString stringWithString:@"BGP"]];
    
    TokenProtocol *tokenProtocol = [[[TokenProtocol alloc] initWithView:mainMapView usingTag:@"TP"] autorelease];
    [tokenProtocol setupProtocol];
    tokenProtocol.tokenView = mainMapView.tokenView;
    mainMapView.tokenView.protocolId = @"TP";
	[[NetworkController sharedNetworkController].networkProtocols setObject:tokenProtocol forKey:[NSString stringWithString:@"TP"]];
    
    TokenProtocol *objectProtocol = [[[TokenProtocol alloc] initWithView:mainMapView usingTag:@"OP"] autorelease];
    [objectProtocol setupProtocol];
    objectProtocol.tokenView = mainMapView.objectView;
    mainMapView.objectView.protocolId = @"OP";
    [[NetworkController sharedNetworkController].networkProtocols setObject:objectProtocol forKey:[NSString stringWithString:@"OP"]];
    
    DrawProtocol *drawProtocol = [[[DrawProtocol alloc] initWithView:mainMapView usingTag:@"DP"] autorelease];
    [drawProtocol setupProtocol];
	[[NetworkController sharedNetworkController].networkProtocols setObject:drawProtocol forKey:[NSString stringWithString:@"DP"]];
    
    [[NetworkController sharedNetworkController] startBonjourService];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (IBAction)doSnapToGridButton:(id)sender {
	if (!mainMapView.drawingView.snapToGrid) {
		[self tokenOff];
		[self drawOff];
		[self backgroundOff];
		[self backgroundAllOff];
        [self objectOff];
		[self snapOn];
	} else {
        [self eraseOff];
    }
}

- (void)snapOn {
	if (!mainMapView.drawingView.snapToGrid) {
        tokenScrollView.hidden = NO;
		mainMapView.drawingView.snapToGrid = YES;
        [self fade:snapDrawingButton fromValue:snapDrawingButton.alpha toValue:1.0 withDuration:0.25];
        [mainSelectionView setUpSelectionScroller:mainSelectionView.snapColorViews];
	}
}

- (void)snapOff {
	if (mainMapView.drawingView.snapToGrid) {
		mainMapView.drawingView.snapToGrid = NO;
        [self fade:snapDrawingButton fromValue:snapDrawingButton.alpha toValue:0.4 withDuration:0.25];
        tokenScrollView.hidden = YES;
	}
}

- (IBAction)doErase:(id)sender {
	if (![LoadedImages sharedLoadedImages].eraserActivated) {
		[self eraseOn];
	} else {
        [self eraseOff];
    }
}

- (void)eraseOn {
	if (![LoadedImages sharedLoadedImages].eraserActivated) {
        if (mainSelectionView.alpha == 1.0) {
            [self fade:mainSelectionView fromValue:mainSelectionView.alpha toValue:0.4 withDuration:0.25];
        }
        if (eraserButton.alpha != 1.0) {
            [self fade:eraserButton fromValue:eraserButton.alpha toValue:1.0 withDuration:0.25];
        }
        [LoadedImages sharedLoadedImages].eraserActivated = YES;
        [LoadedImages sharedLoadedImages].selectedSavedColor = [LoadedImages sharedLoadedImages].selectedColor;
		[LoadedImages sharedLoadedImages].selectedColor = [UIColor clearColor];
        [Players sharedLocalPlayer].currentlyMovingToken = nil;
        [LoadedImages sharedLoadedImages].drawingWidth = 50.0;
	}
}

- (void)eraseOff {
	if ([LoadedImages sharedLoadedImages].eraserActivated) {
        if (mainSelectionView.alpha != 1.0) {
            [self fade:mainSelectionView fromValue:mainSelectionView.alpha toValue:1.0 withDuration:0.25];
        }
        if (eraserButton.alpha == 1.0) {
            [self fade:eraserButton fromValue:1.0 toValue:0.4 withDuration:0.25];
        }
        [LoadedImages sharedLoadedImages].eraserActivated = NO;
		[LoadedImages sharedLoadedImages].selectedColor = [LoadedImages sharedLoadedImages].selectedSavedColor;
        [LoadedImages sharedLoadedImages].drawingWidth = 2.0;
	}
}

- (IBAction)doChangeToTokenView:(id)sender {
	if (!mainMapView.tokenView.addTokensIsActivated) {
		[self snapOff];
		[self drawOff];
		[self backgroundOff];
		[self backgroundAllOff];
        [self objectOff];
		[self tokenOn];
	} else {
        [self eraseOff];
    }
}

- (void)tokenOn {
	if (!mainMapView.tokenView.addTokensIsActivated) {
		mainMapView.tokenView.addTokensIsActivated = YES;
		tokenScrollView.hidden = NO;
        [self fade:tokenButton fromValue:tokenButton.alpha toValue:1.0 withDuration:0.25];
		[mainSelectionView setUpSelectionScroller:mainSelectionView.tokenImageViews];
	}
}

- (void)tokenOff {
	if (mainMapView.tokenView.addTokensIsActivated) {
		mainMapView.tokenView.addTokensIsActivated = NO;
        [self fade:tokenButton fromValue:tokenButton.alpha toValue:0.4 withDuration:0.25];
		tokenScrollView.hidden = YES;
	}
}

- (IBAction)doDraw:(id)sender{
	if (![LoadedImages sharedLoadedImages].drawingActivated) {
		[self snapOff];
		[self tokenOff];
		[self backgroundOff];
		[self backgroundAllOff];
        [self objectOff];
		[self drawOn];
	} else {
        [self eraseOff];
    }
}

- (void)drawOn {
	if (![LoadedImages sharedLoadedImages].drawingActivated) {
        tokenScrollView.hidden = NO;
        [LoadedImages sharedLoadedImages].drawingActivated = YES;
        [self fade:freehandDrawingButton fromValue:freehandDrawingButton.alpha toValue:1.0 withDuration:0.25];
        [mainSelectionView setUpSelectionScroller:mainSelectionView.colorViews];
        if (![LoadedImages sharedLoadedImages].eraserActivated) {
            [LoadedImages sharedLoadedImages].drawingWidth = 2.0;
        } else {
            [LoadedImages sharedLoadedImages].drawingWidth = 50.0;
        }
        
	}
}

- (void)drawOff {
	if ([LoadedImages sharedLoadedImages].drawingActivated) {
        tokenScrollView.hidden = YES;
        [self fade:freehandDrawingButton fromValue:freehandDrawingButton.alpha toValue:0.4 withDuration:0.25];
        [LoadedImages sharedLoadedImages].drawingActivated = NO;
	}
}

- (IBAction)doBackground:(id)sender {
	if (!mainMapView.backgroundView.backgroundActivated) {
		[self tokenOff];
		[self drawOff];
		[self snapOff];
		[self backgroundAllOff];
        [self objectOff];
		[self backgroundOn];
	} else {
        [self eraseOff];
    }
}

- (void)backgroundOn {
	if (!mainMapView.backgroundView.backgroundActivated) {
		tokenScrollView.hidden = NO;
		mainMapView.backgroundView.backgroundActivated = YES;
        [self fade:backgroundButton fromValue:backgroundButton.alpha toValue:1.0 withDuration:0.25];
		[mainSelectionView setUpSelectionScroller:mainSelectionView.backgroundImageViews];
	}
}

- (void)backgroundOff {
	if (mainMapView.backgroundView.backgroundActivated) {
		mainMapView.backgroundView.backgroundActivated = NO;
        [self fade:backgroundButton fromValue:backgroundButton.alpha toValue:0.4 withDuration:0.25];
		tokenScrollView.hidden = YES;
	}
}

- (IBAction)doPlayOn:(id)sender {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:toolView cache:YES];
    [UIView setAnimationDuration:0.5];
    [UIView commitAnimations];
    //[self eraseOff];
    [self tokenOff];
    [self drawOff];
    [self snapOff];
    [self backgroundAllOff];
    [self objectOff];
    [self backgroundOff];
    toolBarReturnButton.hidden = NO;
    toolBarRemoveButton.hidden = YES;
    toolView.hidden = YES;
    tokenScrollView.hidden = YES;
    eraserButton.hidden = YES;
	mainMapView.playingActivated = YES;
    [self fade:toolBarRemoveButton fromValue:1.0 toValue:-0.5 withDuration:1.0];
    [self fade:toolBarReturnButton fromValue:-0.5 toValue:1.0 withDuration:1.0];
}

- (IBAction)doPlayOff:(id)sender {
    toolView.hidden = NO;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:toolView cache:YES];
    [UIView setAnimationDuration:0.5];
    [UIView commitAnimations];
    tokenScrollView.hidden = NO;
	mainMapView.playingActivated = NO;
    [self fade:toolBarRemoveButton fromValue:-0.5 toValue:1.0 withDuration:1.0];
    [self fade:toolBarReturnButton fromValue:1.0 toValue:-0.5 withDuration:1.0];
    eraserButton.hidden = NO;
    
    if (mainSelectionView.currentImageViews == mainSelectionView.tokenImageViews) {
        [self tokenOn];
    } else if (mainSelectionView.currentImageViews == mainSelectionView.objectImageViews) {
        [self objectOn];
    } else if (mainSelectionView.currentImageViews == mainSelectionView.mainBackgroundViews) {
        [self backgroundAllOn];
    } else if (mainSelectionView.currentImageViews == mainSelectionView.backgroundImageViews) {
        [self backgroundOn];
    } else if (mainSelectionView.currentImageViews == mainSelectionView.snapColorViews) {
        [self snapOn];
    } else if (mainSelectionView.currentImageViews == mainSelectionView.colorViews) {
        [self drawOn];
    }
}

- (IBAction)doMenuOn:(id)sender {
    menuView.hidden = NO;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:menuView cache:YES];
    [UIView setAnimationDuration:0.5];
    [UIView commitAnimations];
    [self fade:mainMenuRemoveButton fromValue:-0.5 toValue:1.0 withDuration:1.0];
    [self fade:mainMenuReturnButton fromValue:1.0 toValue:-0.5 withDuration:1.0];
}

- (IBAction)doMenuOff:(id)sender {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:menuView cache:YES];
    [UIView setAnimationDuration:0.5];
    [UIView commitAnimations];
    menuView.hidden = YES;
    [self fade:mainMenuRemoveButton fromValue:1.0 toValue:-0.5 withDuration:1.0];
    [self fade:mainMenuReturnButton fromValue:-0.5 toValue:1.0 withDuration:1.0];
}

- (IBAction)doAllBackground:(id)sender {
	if (!mainSelectionView.changeMainBackgroundsMode) {
		[self tokenOff];
		[self drawOff];
		[self snapOff];
		[self backgroundOff];
		[self objectOff];
        [self backgroundAllOn];
	}
}

- (void)backgroundAllOn {
	if (!mainSelectionView.changeMainBackgroundsMode) {
        [mainSelectionView selectMainBackgroundIcon:map.backgroundImage];
        eraserButton.hidden = YES;
		tokenScrollView.hidden = NO;
		mainSelectionView.changeMainBackgroundsMode = YES;
        mainMapView.backgroundView.changeAllBackgroundActivated = YES;
        [self fade:mainBackgroundButton fromValue:mainBackgroundButton.alpha toValue:1.0 withDuration:0.25];
		[mainSelectionView setUpSelectionScroller:mainSelectionView.mainBackgroundViews];
        if ([LoadedImages sharedLoadedImages].eraserActivated) {
            if (mainSelectionView.alpha != 1.0) {
                [self fade:mainSelectionView fromValue:mainSelectionView.alpha toValue:1.0 withDuration:0.25];
            }
        }
	}
}

- (void)backgroundAllOff {
	if (mainSelectionView.changeMainBackgroundsMode) {
        eraserButton.hidden = NO;
		mainSelectionView.changeMainBackgroundsMode = NO;
        mainMapView.backgroundView.changeAllBackgroundActivated = NO;
        [self fade:mainBackgroundButton fromValue:mainBackgroundButton.alpha toValue:0.4 withDuration:0.25];
		tokenScrollView.hidden = YES;
        if ([LoadedImages sharedLoadedImages].eraserActivated) {
            if (mainSelectionView.alpha == 1.0) {
                [self fade:mainSelectionView fromValue:mainSelectionView.alpha toValue:0.4 withDuration:0.25];
            }
        }
	}
}

- (IBAction)doObject:(id)sender {
    if (!mainMapView.objectView.addObjectsIsActivated) {
		[self tokenOff];
		[self drawOff];
		[self snapOff];
		[self backgroundOff];
        [self backgroundAllOff];
        [self objectOn];
	} else {
        [self eraseOff];
    }
}

- (void)objectOn {
    if (!mainMapView.objectView.addObjectsIsActivated) {
		mainMapView.objectView.addObjectsIsActivated = YES;
		tokenScrollView.hidden = NO;
        [self fade:objectButton fromValue:objectButton.alpha toValue:1.0 withDuration:0.25];
		[mainSelectionView setUpSelectionScroller:mainSelectionView.objectImageViews];
	}
}

- (void)objectOff {
    if (mainMapView.objectView.addObjectsIsActivated) {
		mainMapView.objectView.addObjectsIsActivated = NO;
        [self fade:objectButton fromValue:objectButton.alpha toValue:0.4 withDuration:0.25];
		tokenScrollView.hidden = YES;
	}
}

- (IBAction)doCenterGrid:(id)sender {
	[mainMapView centerView]; 
}

- (IBAction)doCenterGridAtHost:(id)sender {
	[(PlayerProtocol *)[[NetworkController sharedNetworkController].networkProtocols objectForKey:([NSString stringWithString:@"PP"])] sendRequestForPosition];
}

- (IBAction)doGrid:(id)sender {
    ((UIButton *)sender).selected = !((UIButton *)sender).selected;
    mainMapView.gridView.hidden = !mainMapView.gridView.hidden;
}

- (IBAction)doSave:(id)sender {
    [self performSelectorOnMainThread:@selector(disableUI) withObject:nil waitUntilDone:NO];
    [NSThread detachNewThreadSelector:@selector(saveMap) toTarget:self withObject:nil];
}

- (IBAction)doClear:(id)sender {
    [self performSelectorOnMainThread:@selector(disableUI) withObject:nil waitUntilDone:NO];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Clear map" message:@"This will clear the map completely, are you sure you wish to do this?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 1:
            [(PlayerProtocol *)[[NetworkController sharedNetworkController].networkProtocols objectForKey:([NSString stringWithString:@"PP"])] sendClearCommand];
            [map clearMap];
            [mainMapView.backgroundView setNeedsDisplay];
            [mainMapView.drawingView setNeedsDisplay];
            [mainMapView.tokenView setNeedsDisplay];
            [mainMapView.objectView setNeedsDisplay];
        default:
            [self enableUI];
            [alertView release];
    }
}


- (void)saveMap {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    [map saveMap];
    [self performSelectorOnMainThread:@selector(enableUI) withObject:nil waitUntilDone:NO];
    [pool drain];
}

- (void)disableUI {
    dimmingViewOutlet.alpha = 0.3;
    dimmingViewOutlet.hidden = NO;
    [workInProgressView startAnimating];
}

- (void)enableUI {
    dimmingViewOutlet.alpha = 0.0;
    [workInProgressView stopAnimating];
}

- (IBAction)doLogout:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
    [[NetworkController sharedNetworkController] leaveSession];
}

- (void)fade:(UIView *)view fromValue:(float)fromValue toValue:(float)toValue withDuration:(float)duration {
    CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fade.duration = duration;		
    fade.fromValue = [NSNumber numberWithFloat:fromValue]; 
    fade.toValue = [NSNumber numberWithFloat:toValue];
    [view.layer addAnimation:fade forKey:@"fade"];
    if (toValue >= 1.0) {
        view.hidden = NO;
        view.alpha = 1.0;
    } else if (toValue <= 0.0) {
        view.hidden = YES;
        view.alpha = 0.0;
    } else {
        view.alpha = toValue;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
	
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

@end
